import React, { useEffect, useState, useRef } from 'react';
import { leaveChildren } from '@/pages/WorkFlow/components/FormControls/formConfig/custom/leave';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { Form } from 'antd';
import { getLeaveTypeList } from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/components/LeaveType/service';
import { getDataSource } from '@/components/Custom/Time/Time';
import moment from 'moment';
import { getTime } from '@/components/Custom/CustomDatePicker/CustomDatePicker';
import { getFormatByUnit, getLeaveUnit, getTimeExtraParam } from '@/pages/Flow/Mine/ApplyPage/utils';
import request from '@/utils/request';
import { getDurationFlexible } from '@/utils/utils';
import { useRequest } from '@/hooks';

const { Item } = Form;

const Leave = ({ dataSource, form, formValueMap = {} }) => {
    const [items, setItems] = useState([]);
    const { getFieldDecorator } = form;
    const [typeList, setTypeList] = useState([]);
    const [duration, setDuration] = useState(0); // 时长
    const [fileRequire, setFileRequire] = useState(false); // 附件是否必传

    const refForm = useRef(form);

    console.log(duration);
    // 获取请假类型
    const fetchLeaveTypeList = async () => {
        const { companyCode } = formValueMap;
        const { code, data } = await getLeaveTypeList(companyCode);

        if (code === 10000 && data) {
            setTypeList(data);
        }
    };

    const concatTime = ({ time, timeValue }) => {
        if (!timeValue) return time;
        return moment(moment(`${time.format('YYYY-MM-DD')} ${timeValue}:00`));
    };

    const { data: flowlongData, run: runFlowlong } = useRequest(
        params =>
            request('/api/work/v1/attendance/flow/web/flowlong', {
                method: 'POST',
                data: params
            }),
        {
            manual: true
        }
    );

    // 获取时长
    const fetchTimeCount = async (name, value, leaveTypeList, country = 'zh') => {
        // const { fields } = json;
        console.log(1, '-------------------------');
        const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
        if (!value || !value.time) {
            form.setFieldsValue({
                duration: ''
            });
            setDuration('');
            return;
        }

        const {
            leaveType: { key: leaveType },
            startTime,
            endTime
        } = form.getFieldsValue();
        const find = leaveTypeList.find(item => item.leaveCode === leaveType);

        if (!find) return;
        if (value.unit === 2 && !value.dayType) return;
        if (name === 'startTime' && !endTime.time) return;
        if (name === 'endTime' && !startTime.time) return;
        if (name === 'startTime' && endTime.unit === 2 && !endTime.dayType) return;
        if (name === 'endTime' && startTime.unit === 2 && !startTime.dayType) return;
        const currentStart = name === 'startTime' ? value : startTime;
        const currentEnd = name === 'endTime' ? value : endTime;
        const s = concatTime(currentStart);
        const e = concatTime(currentEnd);
        console.log(currentStart, currentEnd, '-------------------------');
        // 如果开始时间和结束时间不正确，则不请求时长
        if (s.isValid() && e.isValid()) {
            // setJson({
            //     ...json,
            //     fields: modifyProps(
            //         'leaveType',
            //         {
            //             startTime: moment(s).format('YYYY-MM-DD hh:mm:00'),
            //             endTime: moment(e).format('YYYY-MM-DD hh:mm:00')
            //         },
            //         fields
            //     )
            // });

            // 上午下午类型要加参数
            const extra = getTimeExtraParam(currentStart, currentEnd, value.unit);
            const postStartTime = getFormatByUnit('startTime', country, find.leaveUnit, s);
            const postEndTime = getFormatByUnit('endTime', country, find.leaveUnit, e);

            runFlowlong({
                attendanceFlowType: 'leave',
                organizationCode: currentUser.currentOrgCode,
                startTime: postStartTime,
                endTime: postEndTime,
                leaveCode: leaveType,
                flowTimeUnit: value.unit,
                ...extra
            });
        }
    };

    // 根据结果显示时长
    useEffect(() => {
        if (flowlongData) {
            const {
                leaveType: { key: leaveType }
            } = refForm.current.getFieldsValue();
            const find = typeList.find(item => item.leaveCode === leaveType);
            if (flowlongData.code === 10000) {
                refForm.current.setFieldsValue({
                    duration: {
                        durationText: getDurationFlexible(flowlongData.data, find.leaveUnit),
                        duration: flowlongData.data.durationLong
                    }
                });
                setDuration(flowlongData.data);
            } else {
                refForm.current.setFields({
                    duration: {
                        value: 0,
                        errors: [new Error(flowlongData.msg)]
                    }
                });
                setDuration('');
            }
        }
    }, [flowlongData, typeList]);

    const handleOnChange = value => {
        const { type } = value;
        // 计算时长
        if (type === 'startTime') {
            // form.validateFields(['endTime'], { force: true });
            if (form.getFieldValue('endTime')) {
                const endTimeValue = form.getFieldValue('endTime');
                // 结束时间多 1 个小时
                form.setFieldsValue(
                    {
                        endTime: {
                            ...endTimeValue,
                            timeValue: value.timeValue
                                ? moment(moment(value.timeValue, 'HH:mm').add(60, 'm')).format('HH:mm')
                                : ''
                        }
                    },
                    () => {
                        // 结束时间赋值完成后需要获取时长
                        fetchTimeCount(
                            'startTime',
                            value,
                            typeList
                            // country: 'zh',
                            // json,
                            // setJson
                        );
                    }
                );
            } else {
                form.setFieldsValue({ endTime: undefined });
            }
        }
        // 计算时长
        if (type === 'endTime') {
            // form.validateFields(['startTime'], { force: true });
            if (form.getFieldValue('startTime')) {
                fetchTimeCount('endTime', value, typeList);
            } else {
                form.setFieldsValue({ startTime: undefined });
            }
        }
    };

    // 选择请假类型 onChange
    const handleOnTypeChange = changeValue => {
        const unit = getLeaveUnit(typeList, changeValue.key);
        const country = 'zh';
        const d = getDataSource(15);
        const nextTime = d.find(newItem => newItem >= moment().format('HH:mm'));
        const endNextTime = moment(moment(nextTime, 'HH:mm').add(60, 'm')).format('HH:mm');

        setFileRequire(typeList.find(v => v.leaveCode === changeValue.key)?.attachmentFlag);

        form.setFieldsValue(
            {
                startTime: {
                    time: getTime({
                        date: moment(),
                        dayType: 'am',
                        unit,
                        country,
                        type: 'startTime'
                    }),
                    type: 'startTime',
                    timeValue: unit === 3 ? nextTime : '',
                    dayType: '',
                    disabled: false,
                    unit,
                    country
                },
                endTime: {
                    time: getTime({
                        date: moment(),
                        dayType: 'pm',
                        unit,
                        country,
                        type: 'endTime'
                    }),
                    type: 'endTime',
                    timeValue: unit === 3 ? endNextTime : '',
                    dayType: '',
                    disabled: false,
                    unit,
                    country
                },
                duration: ''
            },
            () => {
                fetchTimeCount(
                    'startTime',
                    {
                        ...form.getFieldValue('startTime')
                    },
                    typeList,
                    country
                );
            }
        );
        form.validateFields(['startTime', 'endTime'], {
            force: true
        });
    };

    const newConfig = [
        {
            formId: 'leaveType'
        }
    ];

    const mixConfig = (target, source) =>
        // 添加或覆盖特殊配置项
        target.map((v, i) => {
            if (source[i] && v.formId === source[i].formId) {
                v.options = { ...v.options, ...source[i].options };
            }
            return v;
        });

    useEffect(() => {
        fetchLeaveTypeList();
    }, []);

    // 这个地方的逻辑看不懂，不过又不敢改，有个无限递归的嵌套要修复，先修复吧！！！
    useEffect(() => {
        if (dataSource) {
            if (Object.keys(dataSource.children[0]).includes('initialValue')) {
                const c = dataSource.children.map(v => ({ ...v, initialValue: v.initialValue, options: v.options }));
                setItems(c);
            } else {
                setItems(mixConfig(dataSource.children, newConfig));
            }
        } else {
            setItems(leaveChildren);
        }
    }, [dataSource]);

    return (
        <>
            {items.map(v => {
                const { formId, rules, initialValue, extra } = v;
                const o = {};
                const r = rules;

                if (formId === 'leaveType') {
                    o.data = typeList;
                    o.onChange = handleOnTypeChange;
                    o.labelInValue = true;
                    o.mustShowTime = !initialValue;
                }

                if (formId === 'OssUpload') {
                    r[0] = {
                        ...rules[0],
                        required: fileRequire,
                        message: '请上传附件'
                    };
                }

                if (formId === 'startTime' || formId === 'endTime') {
                    o.timeSpread = true;
                    o.onChange = handleOnChange;
                    if (formId === 'startTime') {
                        const endTimeName = 'endTime';
                        r[0] = {
                            ...rules[0],
                            validator(_, value, callback) {
                                const endTime = form.getFieldValue(endTimeName);
                                if (!value || !value.time || (value.unit === 2 && !value.dayType)) {
                                    callback('请选择开始时间！');
                                } else if (moment(value.time) > moment(endTime.time)) {
                                    callback('开始时间不能晚于结束时间！');
                                } else {
                                    callback();
                                }

                                form.validateFields([endTimeName]);
                            }
                        };
                    }

                    if (formId === 'endTime') {
                        const startTimeName = 'startTime';
                        r[0] = {
                            ...rules[0],
                            validator(_, value, callback) {
                                const startTime = form.getFieldValue(startTimeName);
                                if (!value || !value.time || (value.unit === 2 && !value.dayType)) {
                                    callback('请选择结束时间！');
                                } else if (moment(value.time) < moment(startTime.time)) {
                                    callback('结束时间不能早于开始时间！');
                                } else {
                                    callback();
                                }

                                form.validateFields([startTimeName]);
                            }
                        };
                    }
                }

                if (formId === 'duration') {
                    r[0] = {
                        ...rules[0],
                        validator(_, value, callback) {
                            if (value === 0) {
                                callback('时长不能为 0！');
                            } else if (!value) {
                                callback('时长不能为空！');
                            } else {
                                callback();
                            }
                        }
                    };
                }

                return (
                    <Item label={v.label} key={v.formId} extra={extra}>
                        {getFieldDecorator(v.formId, {
                            initialValue,
                            rules: r
                        })(<AutoRenderComponent {...o} config={v} form={form} />)}
                    </Item>
                );
            })}
        </>
    );
};

export default Leave;
